from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, List, Dict, Any
from app.utils.permissions import require_permissions
from app.services.statistics_service import StatisticsService
from app.config.logging_config import get_logger
from app.services.user_service import UserInDB
from .auth import get_current_user
from app.utils.permissions import require_data_access

logger = get_logger(__name__)
router = APIRouter()

@router.get("/overview")
@require_permissions(["data_statistics"])
@require_data_access()
async def get_statistics_overview(
    current_user: UserInDB = Depends(get_current_user),
    allowed_customs_codes: Optional[List[str]] = None
):
    """获取统计概览"""
    try:
        service = StatisticsService()
        stats = await service.get_user_statistics_overview(
            current_user, 
            allowed_customs_codes
        )
        return stats
    except Exception as e:
        logger.error(f"获取统计概览失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取统计概览失败")

@router.get("/detail")
@require_permissions(["data_statistics"])
@require_data_access()
async def get_detailed_statistics(
    start_date: str = Query(..., description="开始日期 (YYYY-MM-DD)"),
    end_date: str = Query(..., description="结束日期 (YYYY-MM-DD)"),
    current_user: UserInDB = Depends(get_current_user),
    allowed_customs_codes: Optional[List[str]] = None
):
    """获取详细统计数据"""
    try:
        service = StatisticsService()
        stats = await service.get_detailed_statistics(
            current_user, 
            start_date, 
            end_date,
            allowed_customs_codes
        )
        return stats
    except Exception as e:
        logger.error(f"获取详细统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取详细统计数据失败")